package com.xxx.lease.web.app.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxx.lease.common.constant.RedisConstant;
import com.xxx.lease.common.exception.LeaseException;
import com.xxx.lease.common.result.ResultCodeEnum;
import com.xxx.lease.common.utils.JwtUtil;
import com.xxx.lease.common.utils.VerifyCodeUtil;
import com.xxx.lease.model.entity.UserInfo;
import com.xxx.lease.model.enums.BaseStatus;
import com.xxx.lease.web.app.service.LoginService;
import com.xxx.lease.web.app.service.SmsService;
import com.xxx.lease.web.app.service.UserInfoService;
import com.xxx.lease.web.app.vo.user.LoginVo;
import com.xxx.lease.web.app.vo.user.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserInfoService userInfoService;


    @Override
    public void getSMSCode(String phone) throws LeaseException {

        if(!StringUtils.hasText(phone)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //验证码的key
        //app:login:190xxxxx
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + phone;


        //一个手机号一分钟只能发送一次验证码

        Boolean result = stringRedisTemplate.hasKey(key);

        //剩余多长时间过期
        Long expireTime = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
        //验证码实际有效期
        Integer totalTime = RedisConstant.APP_LOGIN_CODE_TTL_SEC;

        if(result) {
            if ((totalTime - expireTime) < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }


        //生成验证码
        String code = VerifyCodeUtil.getVerifyCode(6);
        //发送验证码
        smsService.sendCode(phone, code);
        //存储验证码
        stringRedisTemplate.opsForValue().set(key, code, totalTime, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) throws LeaseException {

        if(!StringUtils.hasText(loginVo.getPhone())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        if (!StringUtils.hasText(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        String key = RedisConstant.ADMIN_LOGIN_PREFIX + loginVo.getPhone();

        String code = stringRedisTemplate.opsForValue().get(key);

        if(code == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }

        if (!code.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();

        UserInfo userInfo = userInfoService.getOne(queryWrapper.eq(UserInfo::getPhone, loginVo.getPhone()));

        if(userInfo == null){
             userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-" + loginVo.getPhone().substring(7));
            userInfoService.save(userInfo);
        }

        if (userInfo.getStatus().equals(BaseStatus.DISABLE)){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        return JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
    }

    @Override
    public UserInfoVo getUserInfoById(Long userId) {

        UserInfo userInfo = userInfoService.getById(userId);

        return new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
    }
}
